import {
	md5
} from "js-md5";
const com = {
	mpTitle: "章鱼智慧阅读",
	serviceURL: "https://readingapi.zysg.cc",
	getAppID: () => {
		const accountInfo = uni.getAccountInfoSync();
		return accountInfo.miniProgram.appId;
	},
	setToken: (val) => {
		uni.setStorageSync('token', val)
	},
	getToken: () => {
		return uni.getStorageSync('token')
	},
	clearToken: () => {
		uni.clearStorageSync('token')
	},
	clearUserInfo: () => {
		uni.clearStorageSync('user')
	},
	setUserInfo: (data) => {
		uni.setStorageSync('user', JSON.stringify(data))
	},
	getUserInfo: () => {
		try {
			return JSON.parse(uni.getStorageSync('user'))
		} catch (e) {
			return null
		}
	},
	goBack: () => {
		uni.navigateBack().catch(e => {
			return
		})
	},
	go: (url) => {
		uni.navigateTo({
			url: '/pages/' + url
		})
	},
	currentPages: () => {
		let ps = getCurrentPages()
		let res = null
		try {
			res=ps[ps.length-1].route
		}catch(e){
			console.log('com.currentPages:',e)
			res=null
		}
		return res
	},
	getParams: (url) => {
		const reg = /(\w+)=([^&]+)/g;
		const params = {};
		let match;

		while ((match = reg.exec(url)) !== null) {
			params[match[1]] = match[2];
		}

		return params;
	},
	parseQueryString(queryString) {
		const queryParams = {};
		// if (queryString.indexOf('?') !== -1) {
		//     queryString = queryString.split('?')[1];
		// }
		const pairs = queryString.split('&');
		for (let i = 0; i < pairs.length; i++) {
			const pair = pairs[i].split('=');
			if (pair.length === 2) {
				queryParams[pair[0]] = decodeURIComponent(pair[1] || '');
			}
		}
		return queryParams;
	},
	getQueryParam: (url, param) => {
		const urlParams = new URLSearchParams(window.location.search);
		return urlParams.get(param);
	},
	getSign: () => {
		const time = Math.floor(Date.now() / 1000);
		const sign = (md5('NoobMaster17359' + time.toString())).substring(4, 24)
		return {
			time: time,
			sign: sign
		}
	},
	poster: (url, data, method = 'post', done, err, auth = false) => {
		uni.showLoading({
			title: "请稍等"
		})

		if (auth === true) {
			const auth = com.getSign()
			data.time = auth.time
			data.sign = auth.sign
			if (url.indexOf('?') >= 0) url += '&time=' + auth.time + '&sign=' + auth.sign
		}
		return uni.request({
			url: com.serviceURL + url,
			data: JSON.stringify(data),
			method: method,
			header: {
				'authorization': 'Bearer ' + com.getToken()
			},
			success: (e) => {
				uni.hideLoading()
				if (e.data.code === 200) {
					done(e.data)
				} else {
					uni.showToast({
						title: e.data.msg,
						icon: 'none'
					})
					com.clearToken()
					com.clearUserInfo()
					setTimeout(() => {
						com.go('userhome')
					}, 2000)
					return
				}
			},
			fail: (e) => {
				uni.hideLoading()
				err(e)
			}
		})
	}
}

export default com